﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POI.eTransmittal.Enitity;
using DevExpress.Web.ASPxCallback;
using DevExpress.Data.Filtering;
using System.Text;
using POI.eTransmittal.BusinessRule;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using System.Data;
using System.Configuration;
namespace POI.eTransmittal.WebApp
{
    public partial class InquiryIncoming :BasePage 
    {
        const string SESSION_CRITERIA_KEY = "poi.eTransmittal_InquiryIncoming";
        const string SESSION_KEY_EMPLOYEE = "poi.etransmittal_NewIncoming_Emplyee";
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Page_Init(object sender, EventArgs e)
        {
            RegisterXpodatasource(xpodsIncoming,xpoDsInbox,xpoDsContact ,xpodsTransUser );
            if (!IsPostBack)
                Session.Remove(SESSION_CRITERIA_KEY);
            if (Session[SESSION_CRITERIA_KEY] != null)
            {
                xpodsIncoming.Criteria = Session[SESSION_CRITERIA_KEY].ToString();
            }
          
        }
       
     
        protected void gridTransmittal_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            if (e.ButtonID == "custEdit")
            {
                IncomingTransmittal trns = (IncomingTransmittal)gridTransmittal.GetRow(e.VisibleIndex);
                ASPxCallback.RedirectOnCallback("~/PageFrameRegisterIncoming.aspx?notpop=1&log=" + trns.ID);
            }
        }

        protected void gridTransmittal_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            gridTransmittal.DataBind();
        }

        protected void clbPanelEdit_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            int opType = 0;
            int idValue = 1;
            string[] pars = e.Parameter.Split(';');
            switch (pars[opType])
            {
                case "load":
                    FillPopUp(pars[idValue]);
                    break;
                case "save":
                    SavePopUp(pars[idValue],false);
                    break;
                case "distribute":
                    DistributePop(pars[idValue]);
                    break;
            }
           
        }
        protected override void SetErrorMessage(string message)
        {
            if (!hfField.Contains("error"))
                hfField.Add("error", message);
            else
                hfField["error"] = message;
        }
        protected override void SetFlashMessage(string message)
        {
            if (!hfField.Contains("info"))
                hfField.Add("info", message);
            else
                hfField["info"] = message;
        }
        
        private void DistributePop(string p)
        {
            SavePopUp(p, true);
          
        }
       
        private void SavePopUp(string logNo, bool isDistribute)
        {
         //   IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, p);

         
            if (!string.IsNullOrEmpty(logNo))
            {
               
                int Log = Convert.ToInt32(logNo);
                int step = -1;
                bool isErr = false;
                string shareFolder = "";
                try
                {
                    string inbox = cboPopInbox.Text;
                    DateTime receivedDate = dtePopReceivedDate.Date;
                    string subject = txtPopSubject.Text;


                    string remarks = txtPopRemarks.Text;
                    string from = cboPopFrom.Text;

                    string attn = hfField.Contains("Attn") ? hfField["Attn"].ToString() : "";
                    string cc = hfField.Contains("Cc") ? hfField["Cc"].ToString() : "";

                    TempFile file = TempFile.GetFileFromSession(this);
                    step = 1;
                    if (file==null )
                    {
                       
                        CommonBusinessRules.SaveIncoming(CurrentUnitOfWork, logNo, inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks);
                        if (isDistribute)
                        {
                            step = 3;
                            CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log);
                        }

                    }
                    else
                    {
                        step = -1;
                        string ext = Path.GetExtension(file.File.FileName );

                        CommonBusinessRules.CheckExtention(CurrentUnitOfWork, ext);
                        step = 1;
                        string path = CommonBusinessRules.GetIncomingShareFolderToWrite(CurrentUnitOfWork);
                        step = 2;
                        string newFileName = CommonBusinessRules.GetIncomingTransmittalFileName(CurrentUnitOfWork, Log, Path.GetExtension(file.File.FileName));
                        shareFolder = Path.Combine(path, newFileName);
                        file.File.SaveAs(shareFolder);

                        CommonBusinessRules.SaveIncoming(CurrentUnitOfWork, logNo, inbox, receivedDate, subject, from, attn, cc, CurrUserId, remarks, shareFolder, file.File.FileName);
                        if (isDistribute)
                        {
                            step = 3;
                            CommonBusinessRules.DistributeIncomingTransmittal(CurrentUnitOfWork, Log, shareFolder, newFileName);
                        }
                    }
                    //   string cc = .Text;
                   
                }
                catch (Exception ex)
                {
                    isErr = true;
                    switch (step)
                    {
                        case 1:
                            
                            SetErrorMessage("Unable to save data, please contact database administrator.;"+ex.Message);
                            break;
                        case 2:
                            SetErrorMessage("Unable to copy/create the following file :<br/>" + shareFolder+";"+ex.Message);
                            break;
                    
                        case 3:
                            SetErrorMessage("Your transmittal is saved with number:" + Log.ToString() + ", but unable to distribute.<br/>;" + ex.Message.Replace(Environment.NewLine, "<br/>"));
                            break;
                        default:
                            SetErrorMessage("Error;"+ex.Message.Replace(Environment.NewLine, "<br/>"));
                            break;
                    }
                }

                if (!isErr)
                {
                    string op = isDistribute ? "distributed" : "saved";
                    SetFlashMessage("Your Transmittal is " + op + " successfully.");
                }

             //   HandleRedirect(Log);

                TempFile.Clear(this);
                TempFile.DeleteTempfiles(this);
            }
        }

        private void FillPopUp(string p)
        {
            IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, p);
            if (trns != null)
            {
                if (CurrentUserRole != null)
                {
                    if (!CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_INCOMING_TRANSMITTAL))
                    {
                        btnDistribute.ClientEnabled = false;
                        btnSave.ClientEnabled = false;
                    }
                    else
                    {
                        btnDistribute.ClientEnabled = true;
                        btnSave.ClientEnabled = true;
                    }
                }
                lblPopNo.Text = string.Format("{0} ({1})", p, trns.Status);
             
                txtPopRemarks.Text = trns.Remarks;
                dtePopReceivedDate.Date = trns.ReceivedDate;
                txtPopSubject.Text = trns.Subject;
                cboPopFrom.Text = trns.From;
                cboPopInbox.Text = trns.InboxName;
                btePopAttn.Text = trns.AttnNames;
                btePopCc.Text = trns.CcNames;
              //  lnkPopFile.Text = trns.OriginalFileName;
                //lblFile.Text = trns.OriginalFileName;
                btnChange.Text = trns.OriginalFileName;

                btnDistribute.Enabled = (trns.Status == IncomingTransmittal.STATUS_DRAFT);

                if (!hfField.Contains("uncLink"))
                    hfField.Add("uncLink", trns.UncLink);
                else
                    hfField["uncLink"] = trns.UncLink;

                if (!hfField.Contains("Attn"))
                    hfField.Add("Attn", trns.Attn);
                else
                    hfField["Attn"] = trns.Attn;

                if (!hfField.Contains("Cc"))
                    hfField.Add("Cc", trns.Cc);
                else
                    hfField["Cc"] = trns.Cc;
         

                TempFile.Clear(this);
                TempFile.DeleteTempfiles(this);
            }
        }

       
       

         protected void upcPopDoc_FileUploadComplete1(object sender, FileUploadCompleteEventArgs e)
         {
             if (e.UploadedFile != null)
             {
              //   TempFile.StoreTempFile(this, e.UploadedFile);
                 TempFile.StoreToTempFolder(this, e.UploadedFile);
                 e.CallbackData = e.UploadedFile.FileName;
                 e.IsValid = true;
             }
         }

         protected void grdEmployee_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
         {
             //string param = e.Parameters;
             //if (param == "bind")
             //{
             //    Session[SESSION_KEY_EMPLOYEE] = CommonBusinessRules.GetEmployeetable(ConfigurationManager.AppSettings["LDAP_URL"]);
             //    grdEmployee.DataSource = (DataTable)Session[SESSION_KEY_EMPLOYEE];
             //    grdEmployee.DataBind();
             //}
             string[] prms = e.Parameters.Split(';');
             string param = prms[0];
             List<string> ids = new List<string>();
             if (param == "bind")
             {
                 grdEmployee.Selection.UnselectAll();
                 if (prms[1] == "attn")
                 {
                     string attn = btePopAttn.Text;
                     ids.AddRange(attn.Split(';'));
                 }
                 else
                 {
                     string cc = btePopCc.Text;
                     ids.AddRange(cc.Split(';'));
                 }
                 foreach (string id in ids)
                 {
                     if (!string.IsNullOrEmpty(id))
                         grdEmployee.Selection.SelectRowByKey(id);
                 }

                 //Session[SESSION_KEY_EMPLOYEE] = CommonBusinessRules.GetEmployeetable(ConfigurationManager.AppSettings["LDAP_URL"]);
                 //grdEmployee.DataSource = (DataTable)Session[SESSION_KEY_EMPLOYEE];
                 grdEmployee.DataBind();
             }
           
         }

         protected void gridTransmittal_RowDeleted(object sender, DevExpress.Web.Data.ASPxDataDeletedEventArgs e)
         {
             CurrentUnitOfWork.CommitChanges();
         }

         protected void clbCancel_Callback(object source, CallbackEventArgs e)
         {
             IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, e.Parameter);
             if (trns != null)
             {
                 e.Result = trns.OriginalFileName;
                 TempFile.Clear(this);
             }
         }

         protected void hfField_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
         {
             string[] prms = e.Parameter.Split(';');
             string value = "";
             if (prms.Length ==1)
             {
                 TempFile tf = TempFile.GetFileFromSession(this);
                 if (!string.IsNullOrEmpty(tf.TempFileLoc))
                 {
                     value = tf.TempFile_UNC_Link;
                 }
             }
             else
             {
                 IncomingTransmittal trns = CommonBusinessRules.GetIncomingTransmittal(CurrentUnitOfWork, prms[1]);
                 if (trns != null)
                 {
                     value = trns.GetUNC_FileLink();
                 }
             }

             if (!hfField.Contains("uncLink"))
                 hfField.Add("uncLink",value);
             else
                 hfField["uncLink"] = value;
         }

         protected void gridTransmittal_CommandButtonInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCommandButtonEventArgs e)
         {
             if (CurrentUserRole != null)
             {
                 if (!CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_INCOMING_TRANSMITTAL))
                 {
                   
                     if (e.ButtonType != DevExpress.Web.ASPxGridView.ColumnCommandButtonType.Delete ) return;
                     e.Visible = false;
                 }
             }
         }

         protected void gridTransmittal_CustomButtonInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonEventArgs e)
         {
             if (CurrentUserRole != null)
             {
                 if (!CurrentUserRole.AccessRights.Contains(AccessRights.MODIFY_OTHER_INCOMING_TRANSMITTAL))
                 {
                     e.Text = "View";
                 }
             }
         }
    }

}